<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class NoticeController extends Controller
{
     public function getAdd(){

       return view('admin/notice/add');
    }

    public function postInsert(Request $request){
        //dd($request -> all());
        $arr = $request -> except('_token');
        $arr['time'] = date('Y-m-d H:i:s',time());
        //dd($arr);

        $res = DB::table('shop_notice') -> insert($arr);
        //dd($res);

        if($res){
            return redirect('admin/notice/index') -> with('success','添加成功'); 
        }else{
            return back() -> with('error','添加失败!');
            
        }
    }

    public function getIndex(Request $request){
        $count = $request -> input('count',10);
        $search = $request -> input('search','');
        //查询数据 并且分页
        $data = DB::table('shop_notice') -> where('title','like','%'.$search.'%')-> paginate($count);
        $page = $request -> input('page',1);
        $start = ($page - 1) * $count + 1;
        $sum = count(DB :: table('shop_notice') -> where('title','like','%'.$search.'%')->get()); 
        $end = min($page * $count,$sum);
        //返回index页面
        return view('admin/notice/index',['data'=>$data,'request'=>$request -> all(), 'start' => $start, 'end' => $end, 'sum' => $sum]);
    }

    public function getDelete($id){
        $res = DB::table('shop_notice') -> where('id',$id) -> delete();
        if($res){
            return redirect('admin/notice/index') -> with('success','删除成功');
        }else{
            return back() -> with('errror','删除失败');
        }
    }

    public function getEdit($id){
        $data = DB::table('shop_notice') -> where('id',$id) -> first();
        return view('admin/notice/edit',['data' => $data]);
    }

    public function postUpdate(Request $request){
        //dd($request -> all());
        $arr = $request -> except('_token','id');
        $arr['time'] = date('Y-m-d H:i:s',time());
        //dd($arr);
        $res = DB::table('shop_notice') -> where('id',$request -> input('id')) -> update($arr);
        //dd($res);
        if($res){
            return redirect('admin/notice/index') -> with('success','修改成功');
        }else{
            return back() -> with('error','修改失败');
        }
    }
}
